import sys,time
import asyncio
from qasync import QEventLoop,asyncSlot
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QThread, pyqtSignal, QTimer
from threading import Thread

class AsyncWorker(QThread):
    def __init__(self, loop):
        super().__init__()
        self.loop = loop  # 保存主事件循环引用

    def run(self,i):
        self.async_task(i)
    
    @asyncSlot()
    async def async_task(self, i):
        """模拟异步操作（如网络请求）"""
        print(f"异步函数开始运行，参数: {i}")       
        m = 0
        while m < 10:
            #.sleep(1)  # 显式传递事件循环
            asyncio.run(asyncio.sleep(1))
            print(f"计数: {m}")
            m += 1
        return "异步任务完成！"

class MainWindow(QMainWindow):
    def __init__(self, loop):
        super().__init__()
        self.loop = loop
        self.worker = AsyncWorker(loop)  # 传递事件循环给worker
        self.init_ui()
        self.thread=None

    def init_ui(self):
        self.setWindowTitle("协程+PyQt示例")
        self.setGeometry(500, 300, 500, 350)
        
        # 创建按钮
        self.btn_async = QPushButton("启动异步任务")
        self.btn_thread = QPushButton("启动线程任务")
        self.btn_timer = QPushButton("启动定时器")
        
        # 设置更美观的样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #F5F7FA;
            }
            QPushButton {
                background-color: #4F81BD;
                color: white;
                border: none;
                border-radius: 4px;
                min-width: 120px;
                min-height: 30px;
                margin: 8px;
                padding: 8px 16px;
                font-family: "Microsoft YaHei";
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: #6B9CD6;
            }
            QPushButton:pressed {
                background-color: #3A6EA5;
            }
        """)
        
        # 连接信号槽
        self.btn_async.clicked.connect(self.start_async_task)
        self.btn_thread.clicked.connect(self.start_thread_task)
        self.btn_timer.clicked.connect(self.start_timer_task)
        
        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.btn_async)
        layout.addWidget(self.btn_thread)
        layout.addWidget(self.btn_timer)
        
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    # @asyncSlot()
    def start_async_task(self):
        """使用qasync的协程任务"""
        print("启动协程任务...")
        # self.worker.async_task(42) #这样用会卡GUI
        self.thread=self.worker
        # self.thread.sync_task(10)
        self.thread.run(10)

    def start_thread_task(self):
        """使用线程的传统任务"""
        print("启动线程任务...")
        Thread(target=self.sync_task, args=(10,)).start()

    def start_timer_task(self):
        """使用Qt定时器的任务"""
        print("启动定时器任务...")
        self.counter = 0
        self.timer = QTimer()
        self.timer.timeout.connect(self.on_timer)
        self.timer.start(1000)

    def on_timer(self):
        """定时器回调"""
        print(f"定时器计数: {self.counter}")
        self.counter += 1
        if self.counter >= 10:
            self.timer.stop()

    def sync_task(self, count):
        """同步阻塞任务"""
        for i in range(count):
            print(f"线程计数: {i}")
            time.sleep(1)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    
    with loop:
        window = MainWindow(loop)
        window.show()
        sys.exit(app.exec_())